/*
 * author      : dormi330 
 * date        : 2018/7/18
 * description : 确认收货服务
 */

package com.deep.trade.application.order;

import com.deep.trade.common.TradeException;
import com.deep.trade.application.EventHub;
import com.deep.trade.domain.order.OrderRepository;
import com.deep.trade.domain.order.TradeOrder;
import com.deep.trade.domain.order.event.OrderEventFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ConfirmReceiptService {
    private static final int ONLY_ONE_SHOULD_BE_UPDATED = 1;
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    private OrderRepository orderRepository;
    private OrderQueryService orderQueryService;
    private EventHub eventHub;

    @Autowired
    public ConfirmReceiptService(
            OrderQueryService orderQueryService
            , OrderRepository orderRepository
            , EventHub eventHub
    ) {
        this.orderQueryService = orderQueryService;
        this.orderRepository = orderRepository;
        this.eventHub = eventHub;
    }


    @Transactional
    public void confirmReceipt(String tradeOrderId) throws Exception {
        TradeOrder tradeOrder = orderQueryService.assureTradeOrder(tradeOrderId);

        // ====== 领域对象操作 =======
        tradeOrder.finish();

        // ====== 存储 =======
        if (ONLY_ONE_SHOULD_BE_UPDATED != orderRepository.updateTradeOrderStatus(tradeOrder)) {
            throw new TradeException("confirmReceipt fail, db operation fail OR order changed");
        }

        // 领域事件 TODO 考虑事件的分发是否在这里完成
        eventHub.publishEvent(OrderEventFactory.eventFinished(tradeOrder.getId()));
    }
}
